<?php
namespace app\index\controller;
use think\Db;
use think\Request;
use think\Controller;

use excel\Excels as excels;
use think\Exception;
class Index extends Base
{
    // 欢迎
    public function index()
    {
        echo "欢迎";
    }

    // 首页
    public function indexShuJu()
    {
        $where = [];
        $where1 = [];
        if ($this->is_xiaoshou == 1) {
            $where1['username'] = $this->getManageList();
            $where['manage_id'] = $this->getManageList();
        }
        $datas['count1'] = db('crm_customer')->where($where)->count();
        $datas['count2'] = db('crm_manage')->where($where1)->count();
        $datas['count3'] = db('crm_order')->where($where)->count();
        $datas['count4'] = db('crm_product')->count();
        apiReturn(200,'获取成功',$datas);
    }

    // 本月业绩曲线图
    public function yejiChart()
    {
        $data = input();//token

        $today_time = strtotime(date('Y-m-d',time())." 00:00:00");
        $month_days = date('d',time());
        for ($i=0; $i < $month_days; $i++) { 
            $time_array[] = $today_time - $i*(3600*24);
            $day_array[] = "".date("m/d",$today_time - $i*(3600*24))."";
        }
        $day_array = array_reverse($day_array);//数组倒序
        $time_array = array_reverse($time_array);


        $manage_author = $this->getManageAuthor();
        if ($manage_author['is_xiaoshou'] == 1) {
            $where['manage_id'] = $this->getManageList();
        }

        foreach ($time_array as $key => $value) {
            $starttime = intval($value);
            $endtime = $starttime + 24*3600;
            //筛选条件
            $where['order_status'] = array('notin','8');
            $where['date'] = array(array('egt',$starttime),array('elt',$endtime));
            $all_price1 = db('crm_order')->where($where)->sum('total');
            if (empty($all_price1)) {
                $xiadan_price[] = 0;
            }else{
                $xiadan_price[] = intval($all_price1);
            }
        }
        $day_array = implode(',', $day_array);
        $xiadan_price = implode(',', $xiadan_price);

        $datas = array(
            'day_array'=>$day_array,
            'xiadan_price'=>$xiadan_price
        );

        apiReturn(200,'获取公司总业绩成功',$datas);
    }

    // 员工排行柱状图
    public function managePaihang()
    {
        $data = input();//token days(1当日 2本月)
        if (empty($data['days'])) {
            apiReturn(201,'时间不能为空');
        }
        if ($this->is_xiaoshou == 1) {
            $where['a.username'] = $this->getManageList();
        }
        $where['b.is_xiaoshou'] = 1;
        $manageList = db('crm_manage')->alias('a')->join('tp_crm_fenzu b','a.zu_id=b.id')->field('a.id,a.name,a.username')->where($where)->order("b.id ASC,a.id ASC")->select();

        $days = [];
        if ($data['days'] == 1) {
            //员工日排行
            $today_time = strtotime(date('Y-m-d',time())." 00:00:00");
            $starttime = $today_time;
            $endtime = $today_time+24*3600;
            $where2 = array(
                'order_status'=>array('neq',11),
                'date'=>array(array('egt',$starttime),array('elt',$endtime))
            );
            foreach ($manageList as $key => $value) {
                $where2['manage_id'] = $value['username'];
                $days[$key]['name'] = ''.$value['name'].'';
                $manage_price = db('crm_order')->where($where2)->sum('total');
                $days[$key]['price'] = ($manage_price == 0) ? 0 : intval($manage_price);
            }
        }elseif ($data['days'] == 2) {
            //员工月排行
            $beginThismonth=mktime(0,0,0,date('m'),1,date('Y'));
            $endThismonth=mktime(23,59,59,date('m'),date('t'),date('Y'));
            $where3 = array(
                'order_status'=>array('neq',6),
                'date'=>array(array('egt',$beginThismonth),array('elt',$endThismonth))
            );
            foreach ($manageList as $key => $value) {
                $where3['manage_id'] = $value['username'];
                $days[$key]['name'] = ''.$value['name'].'';
                $manage_price = db('crm_order')->where($where3)->sum('total');
                $days[$key]['price'] = ($manage_price == 0) ? 0 : intval($manage_price);
            }
        }else{
            $days = array();
        }
        //从大到小排序
        for ($i=0; $i < count($days)-1; $i++) { 
            for ($j=$i+1; $j < count($days); $j++) { 
                if ($days[$i]['price'] < $days[$j]['price']) {
                    $temp = $days[$i];
                    $days[$i] = $days[$j];
                    $days[$j] = $temp;
                }
            }
        }
           
        apiReturn(200,'获取员工排行榜成功',$days);
    }

    // 上传文件
    public function uploadOneFile(Request $request)
    {
        // 指定允许其他域名访问
        header('Access-Control-Allow-Origin:*');
        // 响应类型
        header('Access-Control-Allow-Methods:POST'); 
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type,Token");
        try {
            $file = request()->file('file');
            apiReturn(200,'ok', uploadOss($file));
        } catch (Exception $e) {
            apiReturn(201,'上传失败');
        }
        
    }

    // 分组列表
    public function fenzuList()
    {
        $data = input();//token

        $data['username'] = $this->username;
        
        $where = [];
        $where['is_xiaoshou'] = 1;
        if (isset($data['username'])) {
            if (!empty($data['username'])) {
                $whereid = $this->getFenzuList();
                if (!empty($whereid)) {
                    if (!isset($data['type'])) {
                        $where['id'] = $whereid;
                    }
                }
            }
        }
        $fenzuList = db('crm_fenzu')->field('id,name')->where($where)->order('id ASC')->select();
        apiReturn(200,'获取分组列表成功',$fenzuList);
    }

    // 教务分组列表
    public function jiaowufenzuList()
    {
        $data = input();//token
        $where = [];
        $where['is_xiaoshou'] = 1;
        $where['id'] = ['in','4,5,6,10,11,12,13,14,24,26,27'];
        $fenzuList = db('crm_fenzu')->field('id,name')->where($where)->order('id ASC')->select();
        apiReturn(200,'获取分组列表成功',$fenzuList);
    }

    // 工号列表
    public function manageList()
    {
        $data = input();//token username zu_id

        $data['username'] = $this->username;

        $where = [];
        $where['status'] = 1;
        $whereusername = $this->getManageList();
        if (!empty($whereusername)) {
            if (!isset($data['type'])) {
                $where['username'] = $whereusername;
            }
        }

        if (isset($data['zu_id'])) {
            if (!empty($data['zu_id'])) {
                $zuManageList = db('crm_manage')->where('zu_id',$data['zu_id'])->column('username');
                $where['username'] = array('in',implode(',', $zuManageList));
            }
        }
        // var_dump($where);exit;

        $manageList = db('crm_manage')->field('id,username,name')->where($where)->order('zu_id ASC,id ASC')->select();
        if(isset($data['zu_id'])) {
            $zu_name = db('crm_fenzu')->where('id',$data['zu_id'])->value('name');
        }
        foreach ($manageList as $key => $value) {
            if(isset($data['zu_id'])) {
                if ($zu_name == '客服部') {
                    if ($value['username'] != 93000) {
                        unset($manageList[$key]);
                    }
                }
            }
        }
        apiReturn(200,'获取工号列表成功',$manageList);
    }

    // 客服微信列表
    public function weixinList()
    {
        $data = input();//token manage_id
        $where['status'] = 1;
        if (isset($data['username'])) {
            if (!empty($data['username'])) {
                $where['manage_id'] = $data['username'];
            }
        }
        $weixinList = db('crm_weixin')->field('id,weixin')->where($where)->order('id ASC')->select();
        apiReturn(200,'获取微信列表成功',$weixinList);
    }

    // 设置列表
    public function settingList()
    {
        $data = input();//token type设置类型(1客户等级 2客户标签 3意向 4年级 5快递列表 6跟进标签 7收款账户 8来源) pay_type(后台微信支付 支付宝转账 银行对公转账 付呗 微信转账)

        if (empty($data['type'])) {
            apiReturn(201,'类型不能为空');
        }
        if ($data['type'] == 1) {
            $where['type'] = 15;
        }elseif ($data['type'] == 2) {
            $where['type'] = 16;
        }elseif ($data['type'] == 3) {
            $where['type'] = 14;
        }elseif ($data['type'] == 4) {
            $where['type'] = 17;
        }elseif ($data['type'] == 5) {
            $where['type'] = 13;
        }elseif ($data['type'] == 6) {
            $where['type'] = 18;
        }elseif ($data['type'] == 7) {
            $where['type'] = 19;
            if (isset($data['pay_type'])) {
                if (!empty($data['pay_type'])) {
                    $where['pay_type'] = $data['pay_type'];
                }
            }
        }elseif ($data['type'] == 8) {
            $where['state'] = 1;
            $settingList = db('crm_media')->field('id,media as name')->where($where)->order('id ASC')->select();
            apiReturn(200,'获取设置列表成功',$settingList);
        }else{
            apiReturn(202,'类型错误');
        }
        $manage_author = $this->getManageAuthor();
        if ($manage_author['manage_type'] == 3) {
            if ($data['type'] == 6) {
                $settingList = [
                    ['id'=>1,'name'=>'普通通话回访'],
                    ['id'=>2,'name'=>'开课电话'],
                    ['id'=>3,'name'=>'小灶课'],
                    ['id'=>4,'name'=>'检测电话'],
                    ['id'=>5,'name'=>'续费跟进通话'],
                    ['id'=>6,'name'=>'网络问题']
                ];
                apiReturn(200,'获取设置列表成功',$settingList);
            }
        }
        $where['status'] = 1;
        $settingList = db('crm_setting')->field('id,name')->where($where)->order('id ASC')->select();
        apiReturn(200,'获取设置列表成功',$settingList);
    }

    // 课程列表
    public function courseList()
    {
        $data = input();//token type rows page
        
        $manage_author = $this->getManageAuthor();
        if ($manage_author['manage_type'] == 1 || $manage_author['manage_type'] == 2) {
            $courseList = [];
            if (isset($data['type'])) {
                $courseList1 =  db('goods')->field('id,title,desc,search_type,type,time')->where(array('search_type'=>array('in','1,2,3'),'status'=>1,'time'=>['>',time()-3600*24*7]))->order('time DESC')->select();
                foreach ($courseList1 as $key => $value) {
                    $courseList[] = $value;
                }

                if (strpos($manage_author['group_name'],'经理')) {
                    $where_course = ['id'=>['in','67,78,125,126,98,99,24,194,195,202,203,66,221,220']];
                }else{
                    $where_course = ['id'=>['in','67,78,125,126']];
                }
                $courseList2 =  db('goods')->field('id,title,desc,search_type,type,time')->where($where_course)->select();
                foreach ($courseList2 as $key => $value) {
                    $courseList[] = $value;
                }
                $courseList = self::setCouseListColor($courseList);
                apiReturn(200,'获取课程列表成功',$courseList);
            }else{
                $where['search_type'] = array('in','1,2,3');
                $where1['id'] = array('notin','67,78,125,126');
                $courseList = db('goods')->field('id,title,desc,search_type,type,time')->where($where)->where($where1)->order('time DESC')->select();
                $courseList = self::setCouseListColor($courseList);
                apiReturn(200,'获取课程列表成功',$courseList);
            }
        }elseif ($manage_author['manage_type'] == 3) {
            $courseList = [];
            if (isset($data['type'])) {
                // 记忆力班主任
                if ($manage_author['banzhuren_type'] == 1) {
                    $courseList1 = db('goods')->field('id,title,desc,search_type,type,time')->where(array('search_type'=>array('in','4,5,6'),'status'=>1,'time'=>['>',time()-3600*24*60]))->order('time DESC')->select();
                    foreach ($courseList1 as $key => $value) {
                        $courseList[] = $value;
                    }

                    $courseList3 = db('goods')->field('id,title,desc,search_type,type,time')->where(array('id'=>array('in','108,109','status'=>1)))->limit(0,9)->order('time DESC')->select();
                    foreach ($courseList3 as $key => $value) {
                        $courseList[] = $value;
                    }

                    $courseList2 = db('goods')->field('id,title,desc,search_type,type,time')->where(array('id'=>array('in','24,66,220,203,221,202,194,195,124,259','status'=>1)))->limit(0,20)->order('time DESC')->select();
                    foreach ($courseList2 as $key => $value) {
                        $courseList[] = $value;
                    }
                    $courseList = self::setCouseListColor($courseList);
                    apiReturn(200,'获取课程列表成功',$courseList);    
                //思维导图班主任
                }else{
                    $courseList10 = db('goods')->field('id,title,desc,search_type,type,time')->where(array('search_type'=>array('in','14,15,16'),'status'=>1))->order('time DESC')->select();
                    foreach ($courseList10 as $key => $value) {
                        $courseList[] = $value;
                    }
                    $courseList2 = db('goods')->field('id,title,desc,search_type,type,time')->where(array('id'=>array('in','81,125,126,124,241,242,243,244,245,246,247','status'=>1)))->limit(0,30)->order('time DESC')->select();
                    foreach ($courseList2 as $key => $value) {
                        $courseList[] = $value;
                    }
                    $courseList = self::setCouseListColor($courseList);
                    apiReturn(200,'获取课程列表成功',$courseList);
                }
            }else{
                $where['search_type'] = array('in','4,5,6');
                $courseList = db('goods')->field('id,title,desc,search_type,type,time')->where($where)->order('time DESC')->select();
                $courseList = self::setCouseListColor($courseList);
                apiReturn(200,'获取课程列表成功',$courseList);
            }
        }else{
            $courseList = [];
            if (isset($data['type'])) {
                $courseList1 =  db('goods')->field('id,title,desc,search_type,type,time')->where(array('search_type'=>array('in','1,2,3'),'status'=>1,'time'=>['>',time()-3600*24*7]))->order('time DESC')->select();
                foreach ($courseList1 as $key => $value) {
                    $courseList[] = $value;
                }

                $courseList2 =  db('goods')->field('id,title,desc,search_type,type,time')->where(array('id'=>array('in','67,78')))->select();
                foreach ($courseList2 as $key => $value) {
                    $courseList[] = $value;
                }

                $courseList10 = db('goods')->field('id,title,desc,search_type,type,time')->where(array('search_type'=>array('in','14,15,16'),'status'=>1))->order('time DESC')->select();
                foreach ($courseList10 as $key => $value) {
                    $courseList[] = $value;
                }

                $courseList3 = db('goods')->field('id,title,desc,search_type,type,time')->where(array('search_type'=>array('in','4,5,6'),'status'=>1,'time'=>['>',time()]))->order('time DESC')->select();
                foreach ($courseList3 as $key => $value) {
                    $courseList[] = $value;
                }

                $courseList4 = db('goods')->field('id,title,desc,search_type,type,time')->where(array('id'=>array('in','24,66,220,203,221,202,194,195,125,126,259','status'=>1)))->limit(0,30)->order('time DESC')->select();
                foreach ($courseList4 as $key => $value) {
                    $courseList[] = $value;
                }

                $courseList = self::setCouseListColor($courseList);
                apiReturn(200,'获取课程列表成功',$courseList);
            }else{
                $courseList = db('goods')->field('id,title,desc,search_type,type,time')->where(array('search_type'=>array('in','1,2,3,4,5,6,14,15,16','status'=>1)))->order('time DESC')->select();
                $courseList = self::setCouseListColor($courseList);
                apiReturn(200,'获取课程列表成功',$courseList);
            }
        }
    }

    public function setCouseListColor($courseList)
    {
        foreach ($courseList as $key => &$value) {
            $value['color'] = 0;
            if ($value['search_type'] == 1 || $value['search_type'] == 2 || $value['search_type'] == 3) {
                if (time() < $value['time']) {
                    $xiangcha_days = ceil(($value['time'] - time())/(3600*24));
                    if ($xiangcha_days <= 7) {
                        $value['color'] = 1;
                    }
                }
            }
        }
        return $courseList;
    }

    public function gkkCourseList()
    {
        $courseList =  db('goods')->field('id,title,desc,search_type,type')->where(array('search_type'=>array('in','1,2,3'),'status'=>1))->where(array('id'=>array('notin','67,78')))->order('time DESC')->select();
        apiReturn(200,'获取课程列表成功',$courseList);
    }

    public function zskCourseList()
    {
        $courseList = db('goods')->field('id,title,desc,search_type,type')->where(array('search_type'=>array('in','4,5,6'),'status'=>1))->order('time DESC')->select();
        apiReturn(200,'获取课程列表成功',$courseList);
    }

    public function courseNextList()
    {
        $data = input();//token course_id
        // if (empty($data['course_id'])) {
        //     apiReturn(201,'请选择课程');
        // }
        $list = db('goods_next')->field('id,title,desc')->where(['goods_id'=>['in',$data['course_id']],'status'=>1])->order('sort_order ASC,id ASC')->select();
        apiReturn(200,'获取成功',$list);
    }

    public function courseList2(){

    }



    // 订单商品列表
    public function productList()
    {
        $data = input();//token type_id name sn ids[]产品id数组
        $where['status'] = 1;
        if (isset($data['type_id'])) {
            if (!empty($data['type_id'])) {
                $where['type_id'] = $data['type_id'];
            }
        }
        if (isset($data['name'])) {
            if (!empty($data['name'])) {
                $where['name'] = array('like','%'.$data['name'].'%');
            }
        }
        if (isset($data['sn'])) {
            if (!empty($data['sn'])) {
                $where['sn'] = array('like','%'.$data['sn'].'%');
            }
        }
        if (isset($data['ids'])) {
            if (!empty($data['ids'])) {
                $where['id'] = array('in',implode(',', $data['ids']));
            }
        }
        $productList = db('crm_product')->field('id,name,sn,price')->where($where)->order('id ASC')->select();
        apiReturn(200,'获取课程列表成功',$productList);
    }






    /*
     *主页接口
     *  */

    // 首页长凳数据
    public function indexBench()
    {
        $data = input();//token manage_id time_type(1今日 2本月 3上月)

        $manage_author = $this->getManageAuthor();
        if ($manage_author['is_xiaoshou'] == 1) {
            $where['manage_id'] = $manage_author['username'];
            $where1['manage_id'] = $manage_author['username'];
        }

        $starttime1 = date('Y-m-d 00:00:00',time());
        $endtime1 = date('Y-m-d 23:59:59',time());

        $starttime2 = date('Y-m-d H:i:s',mktime(0,0,0,date("m"),1,date("Y")));
        $endtime2 = date('Y-m-d',mktime(23,59,59,date("m"),date("t"),date("Y")))." 23:59:59";

        $where['date'] = array(array('egt',strtotime($starttime1)),array('elt',strtotime($endtime1)));
        $where1['date'] = array(array('egt',strtotime($starttime2)),array('elt',strtotime($endtime2)));
        $where2['date'] = array(array('egt',strtotime($starttime1)),array('elt',strtotime($endtime1)));
        $where3['date'] = array(array('egt',strtotime($starttime2)),array('elt',strtotime($endtime2)));
        $where['order_status'] = array('notin','1,7,8');
        $where1['order_status'] = array('notin','1,7,8');
        $xiadan_price = db('crm_order')->where($where)->sum('total');
        $xiadan_price1 = db('crm_order')->where($where1)->sum('total');
        if (!empty($where['manage_id'])) {
            $where2['manage_id'] = $where['manage_id'];
        }
        if (!empty($where1['manage_id'])) {
            $where3['manage_id'] = $where1['manage_id'];
        }
        $source=['source'=>['not like','%未付款%']];
        $customer_number = db('crm_customer')->where($where2)->where($source)->count();
        $customer_number1 = db('crm_customer')->where($where3)->where($source)->count();

        $datas = array(
            'customer_number'=>$customer_number,
            'xiadan_price'=>intval($xiadan_price),
            'customer_number1'=>$customer_number1,
            'xiadan_price1'=>intval($xiadan_price1)
        );
        apiReturn(200,'获取首页长凳数据成功',$datas);
    }

    

    // 员工业绩排行
    public function manageRankList()
    {
        $data = input();//token time_type(1今日 2昨日 3本月 4上月) manage_type(1全部 2教务 3学管)

        if ($data['time_type'] == 1) {
            $starttime = date('Y-m-d 00:00:00',time());
            $endtime = date('Y-m-d 23:59:59',time());
        }elseif ($data['time_type'] == 2) {
            $starttime = date('Y-m-d',strtotime("-1 day"))." 00:00:00";
            $endtime = date('Y-m-d',strtotime("-1 day"))." 23:59:59";
        }elseif ($data['time_type'] == 3) {
            $starttime = date('Y-m-d H:i:s',mktime(0,0,0,date("m"),1,date("Y")));
            $endtime = date('Y-m-d',mktime(23,59,59,date("m"),date("t"),date("Y")))." 23:59:59";
        }elseif ($data['time_type'] == 4) {
            $starttime = date('Y-m-01 00:00:00',strtotime("-1 month"));
            $endtime = date('Y-m-d 23:59:59',strtotime(-date("d")."day"));
        }elseif ($data['time_type'] == 5) {
            $starttime = date("Y-m-d H:i:s",strtotime(date("Y",time())."-1"."-1"));
            $endtime = date("Y-m-d H:i:s",strtotime(date("Y",time())."-12"."-31"));
        }elseif ($data['time_type'] == 6) {
            $starttime = date('Y-01-01 00:00:00',strtotime("-1 year",time()));
            $endtime = date('Y-12-31 23:59:59',strtotime("-1 year",time()));
        }else{
            $starttime = date('Y-m-d 00:00:00',time());
            $endtime = date('Y-m-d 23:59:59',time());
        }
        // 角色类型
        if (isset($data['manage_type'])) {
            if ($data['manage_type'] == 2) {
                $where['b.type'] = 2;
            }elseif ($data['manage_type'] == 3) {
                $where['b.type'] = 3;
            }else{
                $where['b.type'] = ['in','2,3'];
            }
        }else{
            $where['b.type'] = ['in','2,3'];
        }
        // $manage_author = $this->getManageAuthor();
        // if ($manage_author['is_xiaoshou'] == 1) {
        //     $where['manage_id'] = $this->getManageList();
        // }
        $where['a.date'] = array(array('egt',strtotime($starttime)),array('elt',strtotime($endtime)));
        $where['a.order_status'] = array('notin','1,7,8');
        $where['a.check_status'] = array('in','3,4');//财务审核后才算业绩
        $where['a.total'] = array('>',0);

        $manageRankList = db('crm_order')->alias('a')->join('tp_crm_manage b','a.manage_id=b.username')->field('a.id,a.manage_id,sum(a.total) as money')->where($where)->group('a.manage_id')->order('money desc')->limit(0,10)->select();

        // $manageRankList = db('crm_order')->field('id,manage_id,sum(total) as money')->where($where)->group('manage_id')->order('money desc')->limit(0,10)->select();

        foreach ($manageRankList as $key => $value) {
            $manageInfo = db('crm_manage')->alias('a')->join('tp_crm_fenzu b','a.zu_id=b.id')->field('a.name,b.name as fenzu_name')->where('a.username',$value['manage_id'])->find();
            $manageRankList[$key]['name'] = $manageInfo['name'];
            $manageRankList[$key]['fenzu_name'] = $manageInfo['fenzu_name'];
            $manageRankList[$key]['money'] = intval($value['money']);
        }

        apiReturn(200,'获取员工排行榜成功',$manageRankList);
    }

    // 分组排行榜
    public function teamRankList()
    {
        $data = input();//token time_type(1今日 2昨日 3本月 4上月)

        

        if ($data['time_type'] == 1) {
            $starttime = date('Y-m-d 00:00:00',time());
            $endtime = date('Y-m-d 23:59:59',time());
        }elseif ($data['time_type'] == 2) {
            $starttime = date('Y-m-d',strtotime("-1 day"))." 00:00:00";
            $endtime = date('Y-m-d',strtotime("-1 day"))." 23:59:59";
        }elseif ($data['time_type'] == 3) {
            $starttime = date('Y-m-d H:i:s',mktime(0,0,0,date("m"),1,date("Y")));
            $endtime = date('Y-m-d',mktime(23,59,59,date("m"),date("t"),date("Y")))." 23:59:59";
        }elseif ($data['time_type'] == 4) {
            $starttime = date('Y-m-01 00:00:00',strtotime("-1 month"));
            $endtime = date('Y-m-d 23:59:59',strtotime(-date("d")."day"));
        }elseif ($data['time_type'] == 5) {
            $starttime = date("Y-m-d H:i:s",strtotime(date("Y",time())."-1"."-1"));
            $endtime = date("Y-m-d H:i:s",strtotime(date("Y",time())."-12"."-31"));
        }elseif ($data['time_type'] == 6) {
            $starttime = date('Y-01-01 00:00:00',strtotime("-1 year",time()));
            $endtime = date('Y-12-31 23:59:59',strtotime("-1 year",time()));
        }else{
            $starttime = date('Y-m-d 00:00:00',time());
            $endtime = date('Y-m-d 23:59:59',time());
        }
        $where['date'] = array(array('egt',strtotime($starttime)),array('elt',strtotime($endtime)));
        $where['order_status'] = array('notin','1,7,8');
        $where['check_status'] = array('in','3,4');//财务审核后才算业绩
        $where['total'] = array('>',0);

        $teamRankList = db('crm_order')->field('id,zu_id,sum(total) as total')->where($where)->group('zu_id')->order('total desc')->limit(0,10)->select();
        foreach ($teamRankList as $key => $value) {
            $teamRankList[$key]['total'] = intval($value['total']);
            $teamRankList[$key]['fenzu_name'] = db('crm_fenzu')->where('id',$value['zu_id'])->value('name');
        }
        apiReturn(200,'获取分组排行榜成功',$teamRankList);
    }

    

    // 待办事项列表
    public function daibanList()
    {
        $data = input();//token status rows page

        $manage_author = $this->getManageAuthor();
        if ($manage_author['is_xiaoshou'] == 1) {
            $where['follow_manage_id'] = $this->getManageList();
        }else{
            $where['follow_manage_id'] = $manage_author['username'];
        }
        $where['status'] = $data['status'];
        $where['wait_deal'] = 1;

        $customerFollowList = db('crm_customer_follow')->where($where)->limit(($data['page']-1)*$data['rows'],$data['rows'])->order('date DESC')->select();
        $count = db('crm_customer_follow')->where($where)->count();

        $datas = array(
            'customerFollowList'=>$customerFollowList,
            'count'=>$count
        );
        apiReturn(200,'获取待办事项列表成功',$datas);
    }

    public function daibanListNew()
    {
        $data = input();//token type follow_type content starttime endtime status rows page
        if (!isset($data['type'])) {
            apiReturn(201,'参数错误');
        }
        if ($data['type'] == 1) {
            $where['a.follow_manage_id'] = $this->username;
        }else{
            $where['a.arrange_manage_id'] = $this->username;
        }
        if (isset($data['follow_type'])) {
            if (!empty($data['follow_type'])) {
                $where['a.follow_type'] = $data['follow_type'];
            }
        }
        if (isset($data['content'])) {
            if (!empty($data['content'])) {
                $where['a.content'] = array('like','%'.$data['content'].'%');
            }
        }
        if (isset($data['starttime']) && isset($data['endtime'])) {
            if (!empty($data['starttime']) && !empty($data['endtime'])) {
                $where['a.date'] = array(array('egt',strtotime($data['starttime'])),array('elt',strtotime($data['endtime'])));
            }
        }
        if (isset($data['status'])) {
            if (!empty($data['status'])) {
                $where['a.status'] = $data['status'];
            }
        }
        if (isset($data['status_self'])) {
            if (!empty($data['status_self'])) {
                $where['a.status_self'] = $data['status_self'];
            }
        }
        if (isset($data['client_id'])) {
            if (!empty($data['client_id'])) {
                $where['a.client_id'] = $data['client_id'];
            }
        }
        if (isset($data['name'])) {
            if (!empty($data['name'])) {
                $where['b.name'] = ['like','%'.$data['name'].'%'];
            }
        }
        if (isset($data['phone'])) {
            if (!empty($data['phone'])) {
                $where['b.phone'] = $data['phone'];
            }
        }
        $where['a.wait_deal'] = 1;

        $customerFollowList = db('crm_customer_follow')->alias('a')->join('tp_crm_customer b','a.client_id=b.client_id')->field('a.*')->where($where)->limit(($data['page']-1)*$data['rows'],$data['rows'])->order('a.date DESC')->select();
        foreach ($customerFollowList as $key => &$value) {
            if (!empty($value['order_id'])) {
                $value['order_total'] = db('crm_order')->where('orderid',$value['order_id'])->value('total');
            }else{
                $value['order_total'] = '';
            }
            $value['jiaowu_manage_name'] = db('crm_manage')->where('username',$value['jiaowu_manage_id'])->value('name');
            $banzhuren = db('crm_manage')->field('name,weixin_id')->where('username',$value['banzhuren_manage_id'])->find();
            if (!empty($banzhuren)) {
                $value['banzhuren_manage_weixin_id'] = $banzhuren['weixin_id'];
                $value['banzhuren_manage_name'] = $banzhuren['name'];
            }else{
                $value['banzhuren_manage_weixin_id'] = null;
                $value['banzhuren_manage_name'] = null;
            }
        }
        $count = db('crm_customer_follow')->alias('a')->join('tp_crm_customer b','a.client_id=b.client_id')->where($where)->count();

        $datas = array(
            'customerFollowList'=>$customerFollowList,
            'count'=>$count
        );
        apiReturn(200,'获取待办事项列表成功',$datas);
    }

    // 完成待办
    public function daibanFinish()
    {
        $data = input();//token id
        if (empty($data['id'])) {
            apiReturn(201,'待办id不存在');
        }

        $ids = explode(',', $data['id']);
        foreach ($ids as $key => $value) {
            $datas['status'] = 2;
            db('crm_customer_follow')->where('id',$value)->update($datas);
        }
        apiReturn(200,'操作成功');
    }

    // 完成待办
    public function daibanFinishSelf()
    {
        $data = input();//token id
        if (empty($data['id'])) {
            apiReturn(201,'待办id不存在');
        }

        $ids = explode(',', $data['id']);
        foreach ($ids as $key => $value) {
            $datas['status_self'] = 2;
            db('crm_customer_follow')->where('id',$value)->update($datas);
        }
        apiReturn(200,'操作成功');
    }

    // 待办备注
    public function daibanBeizhu()
    {
        $data = input();//token id content_beizhu
        if (empty($data['id'])) {
            apiReturn(201,'待办id不存在');
        }
        if (empty($data['content_beizhu'])) {
            apiReturn(201,'备注不能为空');
        }

        $ids = explode(',', $data['id']);
        foreach ($ids as $key => $value) {
            $datas['content_beizhu'] = $data['content_beizhu'];
            db('crm_customer_follow')->where('id',$value)->update($datas);
        }
        apiReturn(200,'操作成功');
    }

    // 客服列表
    public function daibanKefu()
    {
        $where['name'] = ['like','%客服%'];
        $groupids = db('crm_group')->where($where)->column('id');
        $list = db('crm_manage')->field('username,name')->where(['status'=>1,'group_id'=>['in',$groupids]])->select();
        apiReturn(200,'成功',$list);
    }

    // 分配待办
    public function daibanFenpei()
    {
        $data = input();//token id manage_id
        if (empty($data['id'])) {
            apiReturn(201,'待办id不存在');
        }
        if (empty($data['manage_id'])) {
            apiReturn(201,'分配人未选择');
        }

        $ids = explode(',', $data['id']);
        foreach ($ids as $key => $value) {
            $datas['follow_manage_id'] = $data['manage_id'];
            $datas['follow_manage_name'] = db('crm_manage')->where(['username'=>$data['manage_id']])->value('name');
            $data['fenpei_time'] = time();
            db('crm_customer_follow')->where('id',$value)->update($datas);
            db('crm_follow_fenpei')->insert(['follow_id'=>$value,'manage_id'=>$data['manage_id'],'date'=>time()]);
        }
        apiReturn(200,'分配成功');
    }

    // 分配列表
    public function fenpeiList()
    {
        $data = input();//manage_id starttime endtime rows page
        $where = [];
        if (isset($data['starttime']) && isset($data['endtime'])) {
            if (!empty($data['starttime']) && !empty($data['endtime'])) {
                $where['a.date'] = array(array('egt',strtotime($data['starttime'])),array('elt',strtotime($data['endtime'])));
            }
        }
        if (isset($data['manage_id'])) {
            if (!empty($data['manage_id'])) {
                $where['a.manage_id'] = $data['manage_id'];
            }
        }
        $list = db('crm_follow_fenpei')->alias('a')->join('tp_crm_customer_follow b','a.follow_id=b.id')->field('a.id,a.manage_id as fenpei_manage_id,a.date as fenpei_date,b.client_id,b.customer_name,b.arrange_manage_id,b.arrange_manage_name,b.follow_manage_id,b.follow_manage_name,b.follow_type,b.content')->where($where)->order('a.date DESC')->page($data['page'])->limit($data['rows'])->select();
        foreach ($list as $key => &$value) {
            $value['fenpei_manage_name'] = db('crm_manage')->where('username',$value['fenpei_manage_id'])->value('name');
        }
        $count = db('crm_follow_fenpei')->alias('a')->join('tp_crm_customer_follow b','a.follow_id=b.id')->where($where)->count();
        apiReturn(200,'获取成功',['list'=>$list,'count'=>$count]);
    }

    // 分配撤回
    public function fenpeiChehui()
    {
        $data = input();//ids
        if (!isset($data['ids'])) {
            apiReturn(201,'参数错误');
        }
        $ids = explode(',', $data['ids']);
        foreach ($ids as $key => $value) {
            $follow_id = db('crm_follow_fenpei')->where('id',$value)->value('follow_id');
            db('crm_customer_follow')->where(['id'=>$follow_id])->update(['follow_manage_id'=>'93000','follow_manage_name'=>'客服经理']);
            db('crm_follow_fenpei')->where('id',$value)->delete();
        }
        apiReturn(200,'操作成功');
    }

    // 分配班主任
    public function fenpeiBanzhuren()
    {
        $data = input();//token id client_id order_id manage_id
        if (!isset($data['id']) && !isset($data['client_id']) && !isset($data['order_id']) && !isset($data['manage_id'])) {
            apiReturn(201,'参数错误');
        }
        Db::startTrans();
        try {
            $manage_type = db('crm_manage')->where('username',$data['manage_id'])->value('type');
            if ($manage_type != 3) {
                apiReturn(201,'分配人不是班主任');
            }
            $upCustomer = db('crm_customer')->where('client_id',$data['client_id'])->update(['manage_id'=>$data['manage_id'],'banzhuren_manage_id'=>$data['manage_id'],'banzhuren_zhuanyi_date'=>time(),'zhuanyi_date'=>time()]);
            $manage_author = $this->getManageAuthor();
            $content = '从'. $data['client_id'].'转给'.$data['manage_id']."；客服操作产生的";
            $this->followAdd($data['client_id'], $manage_author['username'], '转进客户', $content, 1, $data['manage_id'], date("Y-m-d H:i:s",time()), 0);
            db('crm_order')->where('orderid',$data['order_id'])->update(['banzhuren_manage_id'=>$data['manage_id']]);
            db('crm_customer_follow')->where('id',$data['id'])->update(['banzhuren_manage_id'=>$data['manage_id']]);
            Db::commit();
            apiReturn(200,'分配成功');
        } catch (Exception $e) {
            Db::rollback();
            apiReturn(400,$e->getMessage());
        }
    }

}
